//
//  ContentViewController.m
//  YouMin_iOS
//
//  Created by lanou3g on 15/12/9.
//  Copyright © 2015年 wey. All rights reserved.
//

#import "ContentViewController.h"
#import "OptionButton.h"
#import "UIColor+uitl.h"
#import "UIView+Util.h"
#import "UIImage+Util.h"
@interface ContentViewController ()

@property (nonatomic, strong) UIView *dimView;
@property (nonatomic, strong) UIImageView *blurView;
@property (nonatomic, assign) BOOL isPressed;
@property (nonatomic, strong) NSMutableArray *optionButtons;
@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, assign) CGFloat screenHeight;
@property (nonatomic, assign) CGFloat screenWidth;
@property (nonatomic, assign) CGGlyph length;
@property (nonatomic, strong) UIView *backgroundView;

@end

@implementation ContentViewController

- (UIView *)backgroundView {
    
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc]initWithFrame:self.view.frame];
        _backgroundView.alpha = 0.5;
        _backgroundView.backgroundColor = [UIColor darkGrayColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeFromView:)];
        [_backgroundView addGestureRecognizer:tap];
    }
    return _backgroundView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kRandColor;
    
    UINavigationController *recommendVC = [[UIStoryboard storyboardWithName:@"Recommend" bundle:nil] instantiateViewControllerWithIdentifier:@"recommendVC"];
    recommendVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"推荐" image:nil selectedImage:nil];
    //    [recommendVC.navigationBar setBackgroundImage:[UIImage imageNamed:@"login_btn"] forBarMetrics:UIBarMetricsDefault];
    
    UINavigationController *cityVC = [[UIStoryboard storyboardWithName:@"CIty" bundle:nil] instantiateViewControllerWithIdentifier:@"cityVC"];
    cityVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"城市" image:nil selectedImage:nil];

    UINavigationController *plusVC = [[UIStoryboard storyboardWithName:@"Plus" bundle:nil] instantiateViewControllerWithIdentifier:@"plusVC"];
    [self addCenterButtonWithImage:[UIImage imageNamed:@"navbar_add_hl"]];
    [self setBottomView];
    
    UINavigationController *discoverVC = [[UIStoryboard storyboardWithName:@"Discover" bundle:nil] instantiateViewControllerWithIdentifier:@"discoverVC"];
    discoverVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"发现" image:nil selectedImage:nil];
    
    UINavigationController *myVC = [[UIStoryboard storyboardWithName:@"My" bundle:nil] instantiateViewControllerWithIdentifier:@"myVC"];
    myVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"我的" image:nil selectedImage:nil];
    ///  占位
    self.viewControllers = @[recommendVC,cityVC,plusVC,discoverVC,myVC];
    self.tabBarController.selectedIndex = 0;
    self.tabBar.tintColor = [UIColor blackColor];
    [self.tabBar.items[2] setEnabled:NO];
    
    
}

- (void)setBottomView {
    
    _optionButtons = [NSMutableArray new];
    _screenHeight = [UIScreen mainScreen].bounds.size.height;
    _screenWidth  = [UIScreen mainScreen].bounds.size.width;
    _length = 60;        // 圆形按钮的直径
    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    NSArray *buttonTitles = @[@"文字", @"相册", @"拍照", @"语音", @"扫一扫", @"找人"];
    NSArray *buttonImages = @[@"tweetEditing", @"picture", @"shooting", @"sound", @"scan", @"search"];
    int buttonColors[] = {0xe69961, 0x0dac6b, 0x24a0c4, 0xe96360, 0x61b644, 0xf1c50e};
    
    for (int i = 0; i < 6; i++) {
        OptionButton *optionButton = [[OptionButton alloc] initWithTitle:buttonTitles[i]
                                                                   image:[UIImage imageNamed:buttonImages[i]]
                                                                andColor:[UIColor colorWithHex:buttonColors[i]]];
        
        optionButton.frame = CGRectMake((_screenWidth/6 * (i%3*2+1) - (_length+16)/2),
                                        _screenHeight + 150 + i/3*100,
                                        _length + 16,
                                        _length + [UIFont systemFontOfSize:14].lineHeight + 24);
        
        [optionButton.button setCornerRadius:_length/2];
        optionButton.tag = i;
        optionButton.userInteractionEnabled = YES;
        [optionButton addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapOptionButton:)]];
        [self.view addSubview:optionButton];
        [_optionButtons addObject:optionButton];
    }
}


#pragma mark - 处理点击事件

-(void)addCenterButtonWithImage:(UIImage *)buttonImage
{
    _centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    CGPoint origin = [self.view convertPoint:self.tabBar.center toView:self.tabBar];
    CGSize buttonSize = CGSizeMake(self.tabBar.frame.size.width / 5 - 6, self.tabBar.frame.size.height - 4);
    _centerButton.frame = CGRectMake(origin.x - buttonSize.height/2, origin.y - buttonSize.height/2, buttonSize.height, buttonSize.height);
    [_centerButton setCornerRadius:buttonSize.height/2];
    [_centerButton setBackgroundColor:[UIColor colorWithHex:0x24a83d]];
    [_centerButton setImage:buttonImage forState:UIControlStateNormal];
    [_centerButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    _centerButton.userInteractionEnabled = YES;
    [self.tabBar addSubview:_centerButton];
}

- (void)onTapOptionButton:(UIGestureRecognizer *)recognizer
{
    switch (recognizer.view.tag) {
        case 0: {
            //            TweetEditingVC *tweetEditingVC = [TweetEditingVC new];
            //            UINavigationController *tweetEditingNav = [[UINavigationController alloc] initWithRootViewController:tweetEditingVC];
            //            [self.selectedViewController presentViewController:tweetEditingNav animated:YES completion:nil];
            NSLog(@"0");
            break;
        }
        case 1: {
            //            UIImagePickerController *imagePickerController = [UIImagePickerController new];
            //            imagePickerController.delegate = self;
            //            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            imagePickerController.allowsEditing = NO;
            //            imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            //
            //            [self presentViewController:imagePickerController animated:YES completion:nil];
            NSLog(@"1");
            
            break;
        }
        case 2: {
            //            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
            //                                                                    message:@"Device has no camera"
            //                                                                   delegate:nil
            //                                                          cancelButtonTitle:@"OK"
            //                                                          otherButtonTitles: nil];
            //
            //                [alertView show];
            //            } else {
            //                UIImagePickerController *imagePickerController = [UIImagePickerController new];
            //                imagePickerController.delegate = self;
            //                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            //                imagePickerController.allowsEditing = NO;
            //                imagePickerController.showsCameraControls = YES;
            //                imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            //                imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            //
            //                [self presentViewController:imagePickerController animated:YES completion:nil];
            //            }
            NSLog(@"2");
            break;
        }
        case 3: {
            //            VoiceTweetEditingVC *voiceTweetVC = [VoiceTweetEditingVC new];
            //            UINavigationController *voiceTweetNav = [[UINavigationController alloc] initWithRootViewController:voiceTweetVC];
            //            [self.selectedViewController presentViewController:voiceTweetNav animated:NO completion:nil];
            //
            NSLog(@"3");
            break;
        }
        case 4: {
            //            ScanViewController *scanVC = [ScanViewController new];
            //            UINavigationController *scanNav = [[UINavigationController alloc] initWithRootViewController:scanVC];
            //            [self.selectedViewController presentViewController:scanNav animated:NO completion:nil];
            NSLog(@"4");
            break;
        }
        case 5: {
            //            PersonSearchViewController *personSearchVC = [PersonSearchViewController new];
            //            UINavigationController *personSearchNav = [[UINavigationController alloc] initWithRootViewController:personSearchVC];
            //            [self.selectedViewController presentViewController:personSearchNav animated:YES completion:nil];
            NSLog(@"5");
            break;
        }
        default: break;
    }
    
    [self buttonPressed];
}

- (void)buttonPressed
{
    [self changeTheButtonStateAnimatedToOpen:_isPressed];
    _isPressed = !_isPressed;
}


- (void)changeTheButtonStateAnimatedToOpen:(BOOL)isPressed
{
    
    NSLog(@"%d",isPressed);
    if (isPressed) {
        [self.backgroundView removeFromSuperview];
        [_animator removeAllBehaviors];
        for (int i = 0; i < 6; i++) {
            UIButton *button = _optionButtons[i];
            
            UIAttachmentBehavior *attachment = [[UIAttachmentBehavior alloc] initWithItem:button
                                                                         attachedToAnchor:CGPointMake(_screenWidth/6 * (i%3*2+1),
                                                                                                      _screenHeight + 200 + i/3*100)];
            attachment.damping = 0.65;
            attachment.frequency = 4;
            attachment.length = 1;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC * (6 - i)), dispatch_get_main_queue(), ^{
                [_animator addBehavior:attachment];
            });
        }
        
    } else {
        
        [self back];
    }
}
// 视图出来
- (void)back{
    [self.view addSubview:self.backgroundView];
    [_animator removeAllBehaviors];
    for (int i = 0; i < 6; i++) {
        UIButton *button = _optionButtons[i];
        [self.view bringSubviewToFront:button];
        
        UIAttachmentBehavior *attachment = [[UIAttachmentBehavior alloc] initWithItem:button
                                                                     attachedToAnchor:CGPointMake(_screenWidth/6 * (i%3*2+1),
                                                                                                  _screenHeight - 200 + i/3*100)];
        attachment.damping = 0.65;
        attachment.frequency = 4;
        attachment.length = 1;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.02 * NSEC_PER_SEC * (i + 1)), dispatch_get_main_queue(), ^{
            [_animator addBehavior:attachment];
        });
    }
    
}
- (void)removeFromView:(UIGestureRecognizer *)sender {
     _isPressed = !_isPressed;
    [self changeTheButtonStateAnimatedToOpen:YES];
    [sender.view removeFromSuperview];
}

@end


